package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.atguigu.gulimall.product.config.TempRedisSonConfig;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.annotation.TableField;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;


    @Autowired
    private StringRedisTemplate redisTemplate;

    public CategoryServiceImpl() throws IOException {
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);

        //组装成父子的树形结构


        //找到所有的一级分类
        List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildren(menu, list));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        System.out.println("");
        return level1Menus;
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查单曲的菜单，是否被别的地方引用

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> longs = new ArrayList<>();
        findCateParentId(catelogId, longs);
        return (Long[]) longs.toArray(new Long[longs.size()]);
    }


    /**
     * @CacheEvict:失效模式的使用
     * @param category
     */
//
//    @Caching(evict ={
//            @CacheEvict(value = "category",key = "'getLeavelFirstCategorys'")
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    //清楚缓存中所有数据
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updataCategory(category.getCatId(), category.getName());
        }
    }


    /**
     * 每一个需要缓存的数据我们都来指定要放到哪个名字的缓存【缓存的分区（按照业务类型划分）】
     *  @Cacheable({"catagory"})
     *  1、代表当前方法的结果需要缓存，如果缓存中有，方法不用调用。
     *      如果缓存没有，会调用方法，最后将方法的结果放入缓存
     *  2、默认行为：
     *      1）、如果缓存中有，方法不调用
     *      2）、key默认自动生成，缓存的名字::SimpleKey[](自动生成的key值)
     *      3）、缓存的value的值，默认使用jdb序列化机制。将序列化后的数据存到redis
     *      4）、默认ttl时间 -1；
     *  3、自定义：
     *      1）、指定生成的缓存使用的key，key属性指定，接受一个Spfl
     *      2）、指定缓存的数据的存活时间，配置文件中修改ttl
     *      3）、将数据保存为json格式
     * @return
     */

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLeavelFirstCategorys() {

        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<CategoryEntity>();
        queryWrapper.eq("parent_cid", "0");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(queryWrapper);
        return categoryEntities;
    }


    RedissonClient redisSon= TempRedisSonConfig.getRedisSon();
    /**
     * 高并发缓存问题的解决：
     * 1、缓存穿透：加空结果缓存
     * 2、缓存雪崩：设置过期时间（加随机值）
     * 3、缓存击穿：加锁
     *
     * @return
     */


    @Cacheable(value = "category",key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询数据库。。。。。。。。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查询出所有一级分类
        List<CategoryEntity> leavelFirstCategorys = getLeavelFirstCategorys();


        //封装二级分类和三级分类
        Map<String, List<Catelog2Vo>> parent_cid = leavelFirstCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, 0L);
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(item -> {
                            List<CategoryEntity> level3List = getParent_cid(selectList, v.getCatId());
                            List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                            if (level3List != null) {
                                catelog3VoList = level3List.stream().map(level3Item -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), level3Item.getCatId().toString(), level3Item.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                            }
                            return new Catelog2Vo(v.getCatId().toString(), catelog3VoList, item.getCatId().toString(), item.getName());
                        }).collect(Collectors.toList());
                    }

                    return catelog2Vos;

                }));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisSonLock() {
        /**
         * 只要是同意吧锁，就能锁住这个锁的所有线程
         * 1.将数据库的多次查询变为一次
         */

        //1.锁的名字：锁的粒度，越细越快
        //锁的粒度：具体缓存的是某个数据;
        RLock lock = redisSon.getLock("catalogJson-lock");

        lock.lock();;

        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        /**
         * 只要是同意吧锁，就能锁住这个锁的所有线程
         * 1.将数据库的多次查询变为一次
         */

        //1.占分布式锁，保证原子性
        //2.为防止特殊情况下出现死锁（例如断电），给锁加上过期时间
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功，执行业务
            System.out.println("加锁成功===============");
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                //删除锁，保证原子性
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }

//            redisTemplate.delete("lock");
            return dataFromDB;
        } else {
            System.out.println("加锁失败");

            //加锁失败，重试(自旋)
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }

            return getCatalogJsonFromDBWithRedisLock();
        }

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        //得到锁以后，我们应该再去缓存中确定一次，
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查询出所有一级分类
        List<CategoryEntity> leavelFirstCategorys = getLeavelFirstCategorys();


        //封装二级分类和三级分类
        Map<String, List<Catelog2Vo>> parent_cid = leavelFirstCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, 0L);
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(item -> {


                            List<CategoryEntity> level3List = getParent_cid(selectList, v.getCatId());
                            List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                            if (level3List != null) {
                                catelog3VoList = level3List.stream().map(level3Item -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), level3Item.getCatId().toString(), level3Item.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                            }


                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), catelog3VoList, item.getCatId().toString(), item.getName());
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }

                    return catelog2Vos;

                }));
        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid));
        return parent_cid;


    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        //得到锁以后，我们应该再去缓存中确定一次，
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查询出所有一级分类
        List<CategoryEntity> leavelFirstCategorys = getLeavelFirstCategorys();


        //封装二级分类和三级分类
        Map<String, List<Catelog2Vo>> parent_cid = leavelFirstCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, 0L);
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(item -> {


                            List<CategoryEntity> level3List = getParent_cid(selectList, v.getCatId());
                            List<Catelog2Vo.Catelog3Vo> catelog3VoList = null;
                            if (level3List != null) {
                                catelog3VoList = level3List.stream().map(level3Item -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item.getCatId().toString(), level3Item.getCatId().toString(), level3Item.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                            }


                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), catelog3VoList, item.getCatId().toString(), item.getName());
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }

                    return catelog2Vos;

                }));
        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid));
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    private void findCateParentId(Long catelogId, List<Long> longs) {
        CategoryEntity entity = this.getById(catelogId);
        longs.add(0, entity.getCatId());
        if (entity.getParentCid() != 0) {
            findCateParentId(entity.getParentCid(), longs);
        }
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> list) {
        if (menu.getName().equals("test002")) {
            System.out.println("");
        }
        List<CategoryEntity> children = list.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(menu.getCatId())
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, list));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}